package com.ideaaedi.springcloud.jd.commonspring.oauth2;


import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ideaaedi.springcloud.jd.commonds.entity.BaseCodeMsgEnum;
import com.ideaaedi.springcloud.jd.commonds.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限不足时的处理器
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.A
 */
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) {
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        Result<?> result = Result.failure(BaseCodeMsgEnum.ACCESS_DENY);
        try {
            log.error("visitor access deny. {}.to return result -> {}", accessDeniedException.getMessage() + ". use '" + request.getMethod() + "' to access '" + request.getRequestURI() + "'", JSON.toJSONString(result), accessDeniedException);
            response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        } catch (IOException e) {
            log.error("visitor access deny. to e.getMessage() -> {}", e.getMessage(), accessDeniedException);
        }
    }
}
